package 课上练习0421_scala

import scala.collection.mutable.ListBuffer

/**
 * 偏函数
 */
object Scala_04_partial_function {
  def main(args: Array[String]): Unit = {
    println(f1("one"))
//    println(f1("four")) // 报错
    println(f1.isDefinedAt("four"))// 判断是否在偏函数执行范围内，防止函数中没有匹配项发生异常

    // 案例1：要求只有数字可以加入到List中
    val inc = new PartialFunction[Any, Int] {
      override def apply(v1: Any): Int = v1.asInstanceOf[Int]
      override def isDefinedAt(x: Any): Boolean = x.isInstanceOf[Int]
    }
    val list = ListBuffer(1, 2, 4, "hadoop").collect(inc)
    println(list)

    // 案例2：分别对正数+10，对字符串返回长度
    val list1 = List(1, 3, 5, 67, 6, -8, "hello")
    list1.map({
      case x: Int if x > 0 => x + 10
      case x: String => x.length
      case x => x
    }).foreach(println)
  }

  def f1: PartialFunction[String, Int] = {
    case "one" => 1
    case "two" => 2
    case "three" => 3
//    case _ => 0
  }
}
